package com.db.williamchart.extensions;

import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;

import androidx.core.content.ContextCompat;
import com.db.williamchart.data.DonutDataPoint;

import java.util.Iterator;

public class ExtensionUtils {
    public static void drawChartBar(Canvas canvas, RectF bar, float radius, Paint paint) {
        canvas.drawRoundRect(bar, radius, radius, paint);
    }

    public static void centerAt(Drawable drawable, float x, float y) {
        int drawableHalfWidth = drawable.getIntrinsicWidth() / 2;
        int drawableHalfHeight = drawable.getIntrinsicHeight() / 2;
        drawable.setBounds(
                (int) x - drawableHalfWidth,
                (int) y - drawableHalfHeight,
                (int) x + drawableHalfWidth,
                (int) y + drawableHalfHeight
        );
    }

    public static DonutDataPoint toDonutDataPoint(float value, float offset) {
        return new DonutDataPoint(value + offset, 0f);
    }

    public static TypedArray obtainStyledAttributes(FrameLayout frameLayout, AttributeSet attrsSet, int[] attrsId) {
        return frameLayout.getContext().getTheme().obtainStyledAttributes(attrsSet, attrsId, 0, 0);
    }

    public static int toPx(int value) {
        return (int) (value * Resources.getSystem().getDisplayMetrics().density);
    }

    public static Drawable getDrawable(View view, int drawableRes) {
        return ContextCompat.getDrawable(view.getContext(), drawableRes);
    }

    public static <T, O extends Comparable<O>> O maxValueBy(Iterable<T> iterable, Selector<T, O> selector) {
        Iterator<T> iterator = iterable.iterator();
        if (!iterator.hasNext()) return null;
        T maxElem = iterator.next();
        O maxValue = selector.doSelector(maxElem);
        if (!iterator.hasNext()) return null;
        do {
            T e = iterator.next();
            O v = selector.doSelector(e);
            if (maxValue.compareTo(v) < 0) {
                maxValue = v;
            }
        } while (iterator.hasNext());
        return maxValue;
    }

    public interface Selector<T, O> {
        O doSelector(T value);
    }
}
